package week_five;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class TopVotedCandidate {

    List<int[]> list;

    //准备数据，把投票按时间序列排序，记录每个时间的leader，存入list，然后对list二分查找
    public TopVotedCandidate(int[] persons, int[] times) {
        int leader = -1;
        int m = 0;
        Map<Integer, Integer> count = new HashMap<>();
        list = new ArrayList<>();

        for (int i = 0; i < persons.length; i++) {
            int person = persons[i];
            int vote = count.getOrDefault(person, 0) + 1;
            count.put(person, vote);
            if (m <= vote) {
                leader = person;
                m = vote;
            }
            list.add(new int[]{leader, times[i]});
        }
    }

    public int q(int t) {
        int l = -1, r = list.size() - 1;
        while (l < r) {
            int mid = (r - l + 1) / 2 + l;
            if (list.get(mid)[1] <= t) {
                l = mid;
            } else {
                r = mid - 1;
            }
        }
        return list.get(l)[0];
    }
}


